package com.zhz.common.tool.mybatisplus.base.core.context;

import com.alibaba.ttl.TransmittableThreadLocal;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 用户上下文对象
 * @author zhouhengzhe
 */
public final class ContextHolder {
    private static ThreadLocal<Map<String, Object>> local = new TransmittableThreadLocal<>();

    private ContextHolder() {
    }

    public static <T> T get(String key) {
        Map<String, Object> map = local.get();
        return Objects.isNull(map) ? null : (T) map.get(key);
    }

    public static void set(String key, Object value) {
        Map<String, Object> map = local.get();
        if (Objects.isNull(map)) {
            map = new HashMap(4);
        }

        ((Map) map).put(key, value);
        local.set(map);
    }

    public static void remove() {
        local.remove();
    }
}
